from rest_framework import serializers
from.models import User


class UserLoginSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=32)
    password = serializers.CharField(write_only=True)

    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        # print(f"尝试登录的用户名: {username}")  # 添加调试打印
        user = User.objects.filter(username=username).first()
        if user:
            # print(f"找到用户，正在验证密码")  # 添加调试打印
            if user.check_password(password):
                attrs['user'] = user
            else:
                raise serializers.ValidationError('用户名或密码错误')
        else:
            raise serializers.ValidationError('用户名或密码错误')

        return attrs